/*************************************************************************
	> File Name: udp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/30 22:31
 ************************************************************************/

#pragma once

#include <iostream>
#include <unordered_map>
#include <string>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "log.hpp"

const int SIZE = 1024;

class UdpServer
{
public:
    UdpServer (uint16_t port, std::string ip = ""):_port(port), _sock(-1)
    {}

    bool initServer()
    {
        if ((_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
        if (bind(_sock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "init udp server done ... %s", strerror(errno));
        return true;
    }

    void start()
    {
        char buffer[SIZE];
        std::string echoMessage = "echo:";
        while (1) {
            memset(buffer, 0, sizeof buffer);
            struct sockaddr_in peer;
            bzero(&peer, sizeof peer);
            socklen_t len = sizeof peer;
            ssize_t s = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if (s > 0) {
                uint16_t cli_port = ntohs(peer.sin_port);
                std::string cli_ip = inet_ntoa(peer.sin_addr);
                printf("[%s:%d]# %s\n", cli_ip.c_str(), cli_port, buffer);
                sendto(_sock, (echoMessage + buffer).c_str(), (echoMessage + buffer).size(), 0, (struct sockaddr*)&peer, len);
            }
        }
    }

    virtual ~UdpServer ()
    {
        if (_sock >= 0) {
            close(_sock);
        }
    }

private:
    uint16_t _port;
    std::string _ip;
    int _sock;
};
